import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';

export class ClientVenueController extends BaseController {
  // 获取场地列表（前端应用专用）
  async getVenueList(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { 
        page = 1, 
        limit = 20, 
        city, 
        country, 
        status = 'ACTIVE',
        sortBy = 'sortOrder',
        sortOrder = 'asc'
      } = req.query;
      
      const pageNum = parseInt(page as string);
      const limitNum = parseInt(limit as string);
      const skip = (pageNum - 1) * limitNum;

      // 构建查询条件
      const where: any = {};
      
      if (city) {
        where.city = city;
      }

      if (country) {
        where.country = country;
      }

      if (status) {
        where.status = status;
      }

      // 构建排序条件
      const orderBy: any = {};
      if (sortBy === 'sortOrder') {
        orderBy.sortOrder = sortOrder; // 启用排序字段
      } else if (sortBy === 'name') {
        orderBy.name = sortOrder;
      } else if (sortBy === 'createdAt') {
        orderBy.createdAt = sortOrder;
      } else if (sortBy === 'city') {
        orderBy.city = sortOrder;
      } else {
        // 默认按排序字段升序排列
        orderBy.sortOrder = 'asc';
      }

      // 查询场地列表
      const [venues, total] = await Promise.all([
        prisma.venue.findMany({
          where,
          skip,
          take: limitNum,
          select: {
            id: true,
            name: true,
            description: true,
            address: true,
            city: true,
            country: true,
            status: true,
            capacity: true,
            sortOrder: true, // 启用排序字段
            createdAt: true,
            updatedAt: true,
            _count: {
              select: {
                floors: true,
                performances: true
              }
            }
          },
          orderBy
        }),
        prisma.venue.count({ where })
      ]);

      // 格式化响应数据
      const formattedVenues = venues.map((venue: any) => ({
        ...venue,
        floorCount: venue._count.floors,
        performanceCount: venue._count.performances
      }));

      ResponseUtils.success(res, {
        venues: formattedVenues,
        pagination: {
          total,
          page: pageNum,
          limit: limitNum,
          totalPages: Math.ceil(total / limitNum)
        }
      }, '获取场地列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 搜索场地
  async searchVenues(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { keyword = '', page = 1, pageSize = 20, city, country, sortBy = 'sortOrder', sortOrder = 'asc' } = req.query;
      const skip = (Number(page) - 1) * Number(pageSize);

      // 构建查询条件
      const where: any = {};
      
      if (keyword) {
        where.OR = [
          { name: { contains: keyword as string } },
          { description: { contains: keyword as string } },
          { address: { contains: keyword as string } }
        ];
      }

      if (city) {
        where.city = city;
      }

      if (country) {
        where.country = country;
      }

      where.status = 'ACTIVE';

      // 构建排序条件
      const orderBy: any = {};
      if (sortBy === 'sortOrder') {
        orderBy.sortOrder = sortOrder;
      } else if (sortBy === 'name') {
        orderBy.name = sortOrder;
      } else if (sortBy === 'createdAt') {
        orderBy.createdAt = sortOrder;
      } else if (sortBy === 'city') {
        orderBy.city = sortOrder;
      } else {
        // 默认按排序字段升序排列
        orderBy.sortOrder = 'asc';
      }

      // 查询场馆列表
      const [venues, total] = await Promise.all([
        prisma.venue.findMany({
          where,
          skip,
          take: Number(pageSize),
          include: {
            floors: {
              where: { status: 'ACTIVE' },
              orderBy: { level: 'asc' }
            },
            performances: {
              where: { status: 'SCHEDULED' },
              take: 5,
              orderBy: { startTime: 'asc' },
              include: {
                artist: {
                  select: {
                    id: true,
                    name: true,
                    avatar: true
                  }
                }
              }
            },
            _count: {
              select: {
                floors: true,
                performances: true
              }
            }
          },
          orderBy
        }),
        prisma.venue.count({ where })
      ]);

      ResponseUtils.success(res, {
        items: venues,
        pagination: {
          total,
          page: Number(page),
          pageSize: Number(pageSize),
          totalPages: Math.ceil(total / Number(pageSize))
        }
      }, '搜索场地成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取场馆详情
  async getVenueById(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const venueId = parseInt(id);

      if (isNaN(venueId)) {
        ResponseUtils.badRequest(res, '无效的场馆ID');
        return;
      }

      const venue = await prisma.venue.findUnique({
        where: { 
          id: venueId,
          status: 'ACTIVE'
        },
        include: {
          floors: {
            where: { status: 'ACTIVE' },
            orderBy: { level: 'asc' }
          },
          performances: {
            where: { status: 'SCHEDULED' },
            orderBy: { startTime: 'asc' },
            include: {
              artist: {
                select: {
                  id: true,
                  name: true,
                  avatar: true,
                }
              }
            }
          }
        }
      });

      if (!venue) {
        ResponseUtils.notFound(res, '场馆不存在或已停用');
        return;
      }

      ResponseUtils.success(res, venue, '获取场馆详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取热门场馆
  async getPopularVenues(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { limit = 10 } = req.query;

      const venues = await prisma.venue.findMany({
        where: {
          status: 'ACTIVE'
        },
        include: {
          _count: {
            select: {
              performances: true
            }
          }
        },
        orderBy: [
          {
            performances: {
              _count: 'desc'
            }
          },
          {
            name: 'asc'
          }
        ],
        take: Number(limit)
      });

      ResponseUtils.success(res, venues, '获取热门场馆成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取城市列表
  async getCityList(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { country } = req.query;
      
      const where: any = {
        status: 'ACTIVE'
      };
      
      if (country) {
        where.country = country;
      }

      const cities = await prisma.venue.groupBy({
        by: ['city'],
        where,
        _count: {
          city: true
        },
        orderBy: {
          _count: {
            city: 'desc'
          }
        }
      });

      const cityList = cities.map(city => ({
        city: city.city,
        venueCount: city._count.city
      }));

      ResponseUtils.success(res, cityList, '获取城市列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取国家列表
  async getCountryList(_req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const countries = await prisma.venue.groupBy({
        by: ['country'],
        where: {
          status: 'ACTIVE'
        },
        _count: {
          country: true
        },
        orderBy: {
          _count: {
            country: 'desc'
          }
        }
      });

      const countryList = countries.map(country => ({
        country: country.country,
        venueCount: country._count.country
      }));

      ResponseUtils.success(res, countryList, '获取国家列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 根据场馆获取楼层列表
  async getFloorsByVenue(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { venueId } = req.params;
      const { status = 'ACTIVE' } = req.query;

      if (!venueId) {
        return ResponseUtils.sendError(res, { code: 400, message: '场馆ID不能为空' });
      }

      const venueIdNum = parseInt(venueId);
      if (isNaN(venueIdNum)) {
        return ResponseUtils.sendError(res, { code: 400, message: '无效的场馆ID' });
      }

      // 首先验证场馆是否存在
      const venue = await prisma.venue.findUnique({
        where: { id: venueIdNum, status: 'ACTIVE' },
        select: {
          id: true,
          name: true,
          description: true,
          address: true,
          city: true,
          country: true
        }
      });

      if (!venue) {
        return ResponseUtils.sendError(res, { code: 404, message: '场馆不存在或已停用' });
      }

      const floors = await prisma.floor.findMany({
        where: {
          venueId: venueIdNum,
          status: status as any
        },
        orderBy: [
          { level: 'asc' },
          { name: 'asc' }
        ],
        select: {
          id: true,
          venueId: true,
          venue: {
            select: {
              id: true,
              name: true,
              description: true,
              address: true,
              city: true,
              country: true
            }
          },
          name: true,
          level: true,
          description: true,
          floorPlanUrl: true,
          status: true,
          // 关联的演出信息（简化版）
          performances: {
            where: { status: 'SCHEDULED' },
            select: {
              id: true,
              title: true,
              startTime: true,
              endTime: true,
              status: true
            },
            orderBy: { startTime: 'asc' }
          }
        }
      });

      // 格式化返回数据
      const formattedFloors = floors.map((floor) => ({
        ...floor,
        venueId: floor.venueId,
        venue: floor.venue.name,
        performanceCount: floor.performances.length,
        hasActivePerformances: floor.performances.some((p) => p.status === 'SCHEDULED')
      }));

      ResponseUtils.success(res, {
        venue: venue.name,
        venueInfo: venue,
        floors: formattedFloors,
        totalFloors: formattedFloors.length
      }, '获取场馆楼层列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取场馆楼层统计信息
  async getVenueFloorStats(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { venueId } = req.params;

      if (!venueId) {
        return ResponseUtils.sendError(res, { code: 400, message: '场馆ID不能为空' });
      }

      const venueIdNum = parseInt(venueId);
      if (isNaN(venueIdNum)) {
        return ResponseUtils.sendError(res, { code: 400, message: '无效的场馆ID' });
      }

      // 验证场馆是否存在
      const venue = await prisma.venue.findUnique({
        where: { id: venueIdNum, status: 'ACTIVE' },
        select: {
          id: true,
          name: true
        }
      });

      if (!venue) {
        return ResponseUtils.sendError(res, { code: 404, message: '场馆不存在或已停用' });
      }

      // 获取楼层统计信息
      const [totalFloors, activeFloors, floorsWithPerformances] = await Promise.all([
        prisma.floor.count({
          where: { venueId: venueIdNum }
        }),
        prisma.floor.count({
          where: { 
            venueId: venueIdNum, 
            status: 'ACTIVE' 
          }
        }),
        prisma.floor.count({
          where: {
            venueId: venueIdNum,
            status: 'ACTIVE',
            performances: {
              some: {
                status: 'SCHEDULED'
              }
            }
          }
        })
      ]);

      // 获取楼层层级分布
      const levelDistribution = await prisma.floor.groupBy({
        by: ['level'],
        where: { 
          venueId: venueIdNum, 
          status: 'ACTIVE' 
        },
        _count: {
          level: true
        },
        orderBy: {
          level: 'asc'
        }
      });

      const stats = {
        venueId: venueIdNum,
        venueName: venue.name,
        totalFloors,
        activeFloors,
        inactiveFloors: totalFloors - activeFloors,
        floorsWithPerformances,
        levelDistribution: levelDistribution.map(item => ({
          level: item.level,
          count: item._count.level
        }))
      };

      ResponseUtils.success(res, stats, '获取场馆楼层统计信息成功');
    } catch (error) {
      next(error);
    }
  }
}